package web.servlet;

import com.google.gson.Gson;
import commons.DBHelper;
import model.JsonModel;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author zwei
 * @create 2024-05-03 18:38
 */
public class BaseServlet extends HttpServlet {
    protected DBHelper dbHelper=new DBHelper();

    /**
     * 从c中找出  名字为  methodName的方法
     * @param methodName
     * @param c
     * @return
     * @param <T>
     */
    private <T> Method findSetMethod(String methodName, Class<T> c) {
        Method[] ms=c.getDeclaredMethods();
        for(   Method m:ms){
            if(  methodName.equals( m.getName() )){
                return m;
            }
        }
        return null;
    }

    protected <T> T parseObjectFromRequest(HttpServletRequest req,Class<T> cls) throws InstantiationException, IllegalAccessException, InvocationTargetException {
        //1创建T
        T t=cls.newInstance();
        //2取出req中的所有参数
        Map<String,String[]>parametermap=req.getParameterMap();
        for (Map.Entry<String,String[]> entry:parametermap.entrySet()){
            String key=entry.getKey();
            String value=entry.getValue()[0];
            if (value==null||"".equals(value)){
                continue;
            }
            //到cls中找出  set+key
            String methodname="set"+key.substring(0,1).toUpperCase()+key.substring(1);
            Method setMethod=findSetMethod(methodname,cls);
            if (setMethod==null){
                continue;
            }
            Class parameterTypeClass=setMethod.getParameterTypes()[0];
            String parameterTypeName=parameterTypeClass.getName();
            if(  "int".equals(parameterTypeName) || "java.lang.Integer".equals(parameterTypeName)){
                int p=Integer.parseInt( value.toString());
                setMethod.invoke(t, p);
            }else  if(  "float".equals(parameterTypeName) || "java.lang.Float".equals(parameterTypeName)){
                float p=Float.parseFloat( value.toString());
                setMethod.invoke(t, p);
            }else  if(  "double".equals(parameterTypeName) || "java.lang.Double".equals(parameterTypeName)){
                double p=Double.parseDouble( value.toString());
                setMethod.invoke(t, p);
            }else  if(  "byte".equals(parameterTypeName) || "java.lang.Byte".equals(parameterTypeName)){
                byte p=Byte.parseByte( value.toString());
                setMethod.invoke(t, p);
            }else  if(  "long".equals(parameterTypeName) || "java.lang.Long".equals(parameterTypeName)){
                long p=Long.parseLong( value.toString());
                setMethod.invoke(t, p);
            }else  if(  "short".equals(parameterTypeName) || "java.lang.Short".equals(parameterTypeName)){
                short p=Short.parseShort( value.toString());
                setMethod.invoke(t, p);
            }else {
                //激活setMothod
                setMethod.invoke(t, value.toString());
            }
        }
        return t;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException {
        String op=req.getParameter("op");
        JsonModel jm=new JsonModel();
        try {
            if (op==null||"".equals(op)){
                jm.setCode(0);
                jm.setError("op参数不能为空");
                writeJson(jm,resp);
                return;
            }
            Method[] ms=this.getClass().getDeclaredMethods();
            for (Method m:ms){
                if (m.getName().equals(op)){
                    m.invoke(this,req,resp);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            jm.setCode(0);
            jm.setError(e.getMessage());
            writeJson(jm,resp);
        }
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");     //响应流编码
        //resp.setContentType("text/html;charset=utf-8");  //设置html内容编码
        super.service(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
    protected void writeJson(JsonModel jm,HttpServletResponse resp) throws IOException {
        resp.setContentType(("text/json;charset=utf-8"));
        PrintWriter out=resp.getWriter();
        Gson g=new Gson();
        out.println(g.toJson(jm));
        out.flush();
        out.close();
    }
    protected void writeObjectToJson(Object obj,HttpServletResponse resp) throws IOException {
        resp.setContentType(("text/json;charset=utf-8"));
        PrintWriter out=resp.getWriter();
        Gson g=new Gson();
        out.println(g.toJson(obj));
        out.flush();
        out.close();
    }
}
